"""
Place this file into your ~/.bazaar/plugins directory.
To use, you need the following variables set in your ~/.bazaar/bazaar.conf file:
    BREaST_domain = http://path.to.BREaST/
    BREaST_auth = your_BREaST_feed_token
    bugtracker_breast_url = http://path.to.BREaST/viewBug.php?id={id}
To fix bug #123 in a commit:
    bzr commit --fixes breast:123
"""

from bzrlib import branch, errors
from configobj import ConfigObj
import os
import urllib
import urllib2

def breast_hook( local, master, old_revno, old_revid, future_revno, future_revid, tree_delta, future_tree ):
    config = ConfigObj( os.path.expanduser( '~' ) + '/.bazaar/bazaar.conf' )
    branch = local or master
    revision = branch.repository.get_revision( future_revid )

    if revision.iter_bugs() != None:
        bugs = []
        for result in revision.iter_bugs():
            bugs.append( result[0][result[0].find( '=' ) + 1:] )
        check = urllib2.urlopen( config['BREaST_domain'] + 'closeBug.php?auth=' + config['BREaST_auth'] + '&id[]=' + '&id[]='.join( bugs ) + '&branch=' + urllib.quote_plus( branch.nick ) + '&rev=' + str( future_revno ) )
        result = check.read()
        if result:
            raise errors.BzrError( result )
        check.close()

branch.Branch.hooks.install_named_hook( 'pre_commit', breast_hook, 'BREaST hook' )
